﻿(function($){
	var support = $.support.placeholder = "placeholder" in document.createElement("input"),
		valfn = $.fn.val,
		settings;
	
	settings = $.placeholderSettings = {
		wrapClass: "pencil-placeholder-wrap",
		labelClass: "pencil-placeholder-text"
	};
	
	$.fn.placeholder = function(options){
		var input,
			id,
			label,
			wrap;
		
		if(!support){
			input = $(this[0]);
			if(!input.data("__initialize.placeholder__")){
				id = input.attr("id");
				
				wrap = $("<span />").addClass(settings.wrapClass);
				id && wrap.attr("id", settings.wrapClass + "___" + id);
		
				label = $("<label />");
				label.addClass(settings.labelClass);
				label.attr("id", settings.labelClass + "___" + id);
				label.attr("for", id);
				label.text(input.attr("placeholder"));
				label.appendTo(wrap);

				input.replaceWith(wrap);
				input.insertBefore(label);
		
				wrap.bind("focusout", function(){
					if(!input.val()){
						label.show();
					}
				});
		
				wrap.bind("focusin", function(){
					label.hide();
				});
		
				input.data("__initialize.placeholder__", true);
				input.data("__label.placeholder__", label);
			}
		}
	
		return this;
	};
	
	
	if(!support){
		$.fn.val = function(key, value){
			var ret = valfn.apply(this, arguments);
				label = this.data("__label.placeholder__");
				
			if(value !== undefined && label){
				label[value !== "" && document.activeElement !== this[0] ? "hide" : "show"]();
			}
			return ret;
		};
		
		$(document).ready(function(){
			$("[placeholder]").each(function(){
				$(this).placeholder();
			});
		
		});
	}
})(jQuery);